﻿`<%@ WebHandler Language="C#" Class="SIPO.Web.AjaxHandler.Transaction.recObjectionHandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using SIPO.Library.DataAccess.Transaction;
using SIPO.Library.DomainObject.Transaction;
using SIPO.Library.DataAccess.Administration;
using SIPO.Library.DomainObject.Administration;
using SIPO.Library.DomainObject.Administration.UserManagement;
using SIPO.Library.DataAccess.Administration.UserManagement;
using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.DataAccess.Administration.Catalog;

using SIPO.Library.Enum;
using SIPO.Web.Support;

using Newtonsoft.Json.Linq;

namespace SIPO.Web.AjaxHandler.Transaction
{
    public class recObjectionHandler : SIPO.Web.BaseHandler
    {
        private recObjectionRepo objectionDal = new recObjectionRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        recDayOffRepo RecDayOffDal = new recDayOffRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recTransactionTypeRepo recTransactionTypeDal = new recTransactionTypeRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private string MethodName = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context));
                    break;
                case ("update"):
                    context.Response.Write(Update(context));
                    break;
                case ("insertresponse"):
                    context.Response.Write(InsertResponse(context));
                    break;
                case ("insertdecision"):
                    context.Response.Write(InsertDecision(context));
                    break;
                case ("delete"):
                    System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);
                    string jsonString = string.Empty;
                    jsonString = context.Server.UrlDecode(sr.ReadToEnd());
                    JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);
                    sr.Close();
                    sr.Dispose();
                    context.Response.Write(Delete(context, jObj));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                case ("getdatadecision"):
                    context.Response.Write(GetDataDecision(context));
                    break;
                case ("getdataresponse"):
                    context.Response.Write(GetListResponse(context));
                    break;
                default:
                    // do nothing
                    break;
            }

        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string GetListResponse(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recObjection.Fields.ObjectionID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recObjection> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(objectionDal.SelectScalar(SQL.Function.Aggregate.Count, recObjection.Fields.ObjectionID, parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = objectionDal.GetListResponse(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetDataDecision";
                log.LogMessage = ex.Message;
                log.LogSource = "recObjectionHandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }
        
        private string GetDataDecision(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);
            
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recObjection.Fields.ObjectionID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recObjection> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(objectionDal.SelectScalar(SQL.Function.Aggregate.Count, recObjection.Fields.ObjectionID, parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = objectionDal.GetListDecision(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetDataDecision";
                log.LogMessage = ex.Message;
                log.LogSource = "recObjectionHandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }
        
        private string GetData(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            if (parameters == "")
            {
                parameters += " WHERE transactions.recObjection.ResponNo IS Null  and transactions.recObjection.DecisionNo IS Null" ;
            }
            
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recObjection.Fields.ObjectionID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "DESC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recObjection> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(objectionDal.SelectScalar(SQL.Function.Aggregate.Count, recObjection.Fields.ObjectionID, parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = objectionDal.GetList(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "recObjectionHandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }

        private string Insert(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var data = context.Request.Form;
                var objectionNo = context.Server.UrlDecode(data["txtNoSurat"]);
                var decodeObjectionDate = context.Server.UrlDecode(data["txtTglSurat"].ToString());
                var objectionDate = string.IsNullOrEmpty(context.Server.UrlDecode(data["txtTglSurat"])) ? (DateTime?)null : Helper.FormatDate(decodeObjectionDate, Helper.Culture.Indonesian);
                var sanctionID = context.Server.UrlDecode(data["ddlSanksi"]);
                var decodeSanctionDate = context.Server.UrlDecode(data["txtTglSanksi"].ToString());
                var sanctionDate = string.IsNullOrEmpty(context.Server.UrlDecode(data["txtTglSanksi"])) ? (DateTime?)null : Helper.FormatDate(decodeSanctionDate, Helper.Culture.Indonesian);
                var transno = context.Server.UrlDecode(data["hfTransNo"]);
                var debtorSectorID = context.Server.UrlDecode(data["ddlDebitur"]);
                var objectionNote = context.Server.UrlDecode(data["txtCatatan"]);
                var sanctionValue = context.Server.UrlDecode(data["txtNilaiSanksi"]);
                var billingNo = context.Server.UrlDecode(data["hfBillingNo"]);
                var sanctionNo = context.Server.UrlDecode(data["hfSanctionNo"]);

                recObjection obj = new recObjection();
                obj.ObjectionNo = objectionNo;
                obj.ObjectionDate = objectionDate.Value;
                obj.SanctionNo = sanctionNo;
                obj.SanctionDate = sanctionDate.Value;
                obj.SanctionValue = Helper.ToDecimal(sanctionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                obj.TransStatus = "Proses";
                obj.TransNo = transno;
                obj.SanctionID = int.Parse(sanctionID);
                obj.DebtorSectorID = int.Parse(debtorSectorID);
                obj.ObjectionValue = null;
                obj.ObjectionNote = objectionNote;
                obj.IsActive = true;
                obj.BillingNo = billingNo;

                if (context.Request.Files.Count > 0)
                {
                    HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;
                    string fileName = data["name"]; // --> name taken from PLUPLOAD!

                    byte[] datas = new byte[hpf.ContentLength];
                    hpf.InputStream.Position = 0;
                    hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                    obj.ObjectionFile = datas;
                    obj.FileNameObjection = fileName;
                    hpf.InputStream.Close();
                    hpf.InputStream.Dispose();
                }

                obj.CreatedDate = DateTime.Now;
                obj.CreatedBy = base.UserLoggedIn;

                recBilling billing = new recBilling();
                billing.BillingNo = billingNo;
                billing.ObjectionNo = objectionNo;
                billing.IsHold = true;
                billing.UpdatedBy = base.UserLoggedIn;
                billing.UpdatedDate = DateTime.Now;

                objectionDal.Save(obj, billing);

                helper.Message = "Data berhasil di simpan !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                if (ex is System.Data.SqlClient.SqlException)
                {
                    var sqlEx = (System.Data.SqlClient.SqlException)ex;
                    helper.Message = sqlEx.Number.ToString() + " - " + sqlEx.Message;
                }
                else
                    helper.Message = ex.Message;

                helper.IsSuccess = false;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "recObjectionHandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Update(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var data = context.Request.Form;
                var objectionNo = context.Server.UrlDecode(data["txtNoSurat"]);
                var decodeObjectionDate = context.Server.UrlDecode(data["txtTglSurat"].ToString());
                var objectionDate = string.IsNullOrEmpty(context.Server.UrlDecode(data["txtTglSurat"])) ? (DateTime?)null : Helper.FormatDate(decodeObjectionDate, Helper.Culture.Indonesian);
                var sanctionID = context.Server.UrlDecode(data["ddlSanksi"]);
                var decodeSanctionDate = context.Server.UrlDecode(data["txtTglSanksi"].ToString());
                var sanctionDate = string.IsNullOrEmpty(context.Server.UrlDecode(data["txtTglSanksi"])) ? (DateTime?)null : Helper.FormatDate(decodeSanctionDate, Helper.Culture.Indonesian);
                var debtorSectorID = context.Server.UrlDecode(data["ddlDebitur"]);
                var objectionValue = context.Server.UrlDecode(data["txtJumlah"]);
                var objectionNote = context.Server.UrlDecode(data["txtCatatan"]);
                var sanctionValue = context.Server.UrlDecode(data["txtNilaiSanksi"]);
                var sanctionNo = context.Server.UrlDecode(data["hfSanctionNo"]);
                var transNo = context.Server.UrlDecode(data["hfTransNo"]);
                var transStatus = context.Server.UrlDecode(data["hfTransStatus"]);
                var objectionID = context.Server.UrlDecode(data["hfID"]);

                recObjection obj = new recObjection();
                obj.ObjectionID = int.Parse(objectionID);
                obj.ObjectionNo = objectionNo;
                obj.ObjectionDate = objectionDate.Value;
                obj.SanctionID = int.Parse(sanctionID);
                obj.SanctionNo = sanctionNo;
                obj.SanctionDate = sanctionDate.Value;
                obj.SanctionValue = Helper.ToDecimal(sanctionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                obj.DebtorSectorID = int.Parse(debtorSectorID);
                //obj.ObjectionValue = Helper.ToDecimal(objectionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian); // because from UI form is id-ID formatted.
                obj.ObjectionNote = objectionNote;
                obj.TransNo = transNo;
                obj.TransStatus = transStatus;
                obj.IsActive = true;
                obj.UpdatedDate = DateTime.Now;
                obj.UpdatedBy = base.UserLoggedIn;

                if (context.Request.Files.Count > 0)
                {
                    HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;
                    string fileName = data["name"]; // --> name taken from PLUPLOAD!

                    byte[] datas = new byte[hpf.ContentLength];
                    hpf.InputStream.Position = 0;
                    hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                    obj.ObjectionFile = datas;
                    obj.FileNameObjection = fileName;
                    hpf.InputStream.Close();
                    hpf.InputStream.Dispose();
                }

                if (context.Request.Files.Count > 0)
                    objectionDal.Update(obj);
                else
                    objectionDal.UpdateWithoutFile(obj);

                helper.Message = "Data berhasil di ubah !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                if (ex is System.Data.SqlClient.SqlException)
                {
                    var sqlEx = (System.Data.SqlClient.SqlException)ex;
                    helper.Message = sqlEx.Number.ToString() + " - " + sqlEx.Message;
                }
                else
                    helper.Message = ex.Message;

                helper.IsSuccess = false;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update";
                log.LogMessage = helper.Message;
                log.LogSource = "recObjectionHandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string InsertResponse(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var data = context.Request.Form;
                var responNo = context.Server.UrlDecode(data["txtNoSurat"]);
                var decodeResponDate = context.Server.UrlDecode(data["txtTglSurat"].ToString());
                var responDate = string.IsNullOrEmpty(context.Server.UrlDecode(data["txtTglSurat"])) ? (DateTime?)null : Helper.FormatDate(decodeResponDate, Helper.Culture.Indonesian);
                var responNote = context.Server.UrlDecode(data["txtCatatan"]);
                var id = context.Server.UrlDecode(data["hfID"]);
                var objectionid = context.Server.UrlDecode(data["hfObjectionId"]);

                recObjection obj = new recObjection();
                obj.ResponNo = responNo;
                obj.ResponDate = responDate.Value;
                obj.ResponNote = responNote;
                obj.ObjectionID = int.Parse(objectionid);
                if (context.Request.Files.Count > 0)
                {
                    HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;
                    string fileName = data["name"]; // --> name taken from PLUPLOAD!

                    byte[] datas = new byte[hpf.ContentLength];
                    hpf.InputStream.Position = 0;
                    hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                    obj.ResponFile = datas;
                    obj.FileNameRespon = fileName;

                    hpf.InputStream.Close();
                    hpf.InputStream.Dispose();
                }
                
                obj.UpdatedDate = DateTime.Now;
                obj.UpdatedBy = base.UserLoggedIn;

                if (context.Request.Files.Count > 0)
                    objectionDal.UpdateResponse(obj);

                else
                    objectionDal.UpdateResponseWithoutFile(obj);

                helper.Message = "Data berhasil di simpan !";
                helper.IsSuccess = true;

            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update";
                log.LogMessage = helper.Message;
                log.LogSource = "recObjectionHandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }


        private string InsertDecision(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();
            var data1 = context.Request.Form;
            var no = context.Server.UrlDecode(data1["hfTambah"]);
            if (no == "1")
            {
                try
                {
                    //ambil Terms Days dari Pembayaran Keberatan dengan kode 17
                    recTransactionType objTransType = recTransactionTypeDal.GetByTransTypeCode(17);

                    var data = context.Request.Form;
                    var SuratKeputusan = context.Server.UrlDecode(data["txtNoSuratKeputusan"]);
                    var decodeDecisionDate = context.Server.UrlDecode(data["txtTglSurat"].ToString());
                    var DecisionDate = string.IsNullOrEmpty(context.Server.UrlDecode(data["txtTglSurat"])) ? (DateTime?)null : Helper.FormatDate(decodeDecisionDate, Helper.Culture.Indonesian);
                    var SuratTanggapan = context.Server.UrlDecode(data["txtNoSuratTanggapan"]);
                    var decodeResponDate = context.Server.UrlDecode(data["txtTglTanggapan"].ToString());
                    var ResponseDate = string.IsNullOrEmpty(context.Server.UrlDecode(data["txtTglTanggapan"])) ? (DateTime?)null : Helper.FormatDate(decodeResponDate, Helper.Culture.Indonesian);
                    var keputusan = context.Server.UrlDecode(data["hfRadio"]);
                    var DecisionNote = context.Server.UrlDecode(data["txtcatatan"]);
                    var DecisionValue = context.Server.UrlDecode(data["txtNilai"]);
                    var ID = context.Server.UrlDecode(data["hfID"]);
                    var objectionNo = context.Server.UrlDecode(data["hfObjectionNo"]);
                    var debtorsectorid = context.Server.UrlDecode(data["hfDebtorSectorId"]);
                    var sanctionno = context.Server.UrlDecode(data["hfSanctionNo"]);
                    var sanctionvalue = context.Server.UrlDecode(data["hfSanctionValue"]); ;
                    var transtypeid = context.Server.UrlDecode(data["hfTransTypeId"]);
                    var billingno = context.Server.UrlDecode(data["hfBillingNo"]);

                    recObjection obj = objectionDal.GetById(int.Parse(ID));
                    obj.DecisionNo = SuratKeputusan;
                    obj.DecisionDate = DecisionDate.Value;
                    obj.ResponNo = SuratTanggapan;
                    obj.ResponDate = ResponseDate;
                    if (keputusan == "Diterima")
                    {
                        obj.DecisionValue = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    }
                    else if (keputusan == "Diterima Sebagian")
                    {
                        obj.DecisionValue = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    }
                    else
                        obj.DecisionValue = Helper.ToDecimal(sanctionvalue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);

                    obj.Decision = keputusan;
                    obj.DecisionNote = DecisionNote;
                    obj.TransStatus = "Selesai";

                    if (context.Request.Files.Count > 0)
                    {
                        HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;
                        string fileName = data["name"]; // --> name taken from PLUPLOAD!

                        byte[] datas = new byte[hpf.ContentLength];
                        hpf.InputStream.Position = 0;
                        hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                        obj.DecisionFile = datas;
                        obj.FileNameDecisionFile = fileName;

                        hpf.InputStream.Close();
                        hpf.InputStream.Dispose();
                    }
                    obj.UpdatedDate = DateTime.Now;
                    obj.UpdatedBy = base.UserLoggedIn;

                    recBilling billing = new recBilling();
                    billing.IsObjectionStatus = true;
                    billing.IsHold = true;
                    billing.BillingDate = DateTime.Now;
                    //billing.PrevBillingNo = billingno;
                    billing.ObjectionNo = objectionNo;
                    billing.DebtorSectorID = Convert.ToInt32(debtorsectorid);
                    billing.CreatedDate = DateTime.Now;
                    billing.CreatedBy = base.UserLoggedIn;
                    billing.DueDate = RecDayOffDal.GetDueDate(DateTime.Now.AddDays(Convert.ToDouble(objTransType.TermDay)).ToString("yyyyMMdd"));
                    billing.ForPayment = "Pembayaran untuk billing " + sanctionno;
                    if (keputusan == "Diterima")
                    {
                        billing.Value = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        billing.Balance = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    }
                    else if (keputusan == "Diterima Sebagian")
                    {
                        billing.Value = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        billing.Balance = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    }
                    else
                    {
                        billing.Value = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        billing.Balance = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    }

                    //--insert baru ke biling, update ke objection
                    if (context.Request.Files.Count > 0)
                        objectionDal.UpdateDecision(obj, billing);
                    else
                        objectionDal.UpdateDecisionWithoutFile(obj, billing);

                    //--data lama pada billing di hapus (sesuai no billing pada saat memilih sanksi)
                    //billing.BillingNo = billingno;
                    //if (context.Request.Files.Count > 0)
                    //    objectionDal.DeleteBillingNo(billing);
                    //else
                    //    objectionDal.DeleteBillingNo(billing);
                    
                    helper.Message = "Data berhasil di simpan !";
                    helper.IsSuccess = true;
                }
                catch (Exception ex)
                {
                    helper.IsSuccess = false;
                    helper.Message = ex.Message;
                }
                finally
                {
                    recLog log = new recLog();
                    log.LogEvent = "Update";
                    log.LogMessage = helper.Message;
                    log.LogSource = "recObjectionHandler.ashx";
                    log.CreatedBy = base.UserLoggedIn;
                    log.CreatedDate = DateTime.Now;
                    logDal.Save(log);
                }
            }
            else
            {
                try
                {
                    var data = context.Request.Form;
                    var SuratKeputusan = context.Server.UrlDecode(data["txtNoSuratKeputusan"]);
                    var decodeDecisionDate = context.Server.UrlDecode(data["txtTglSurat"].ToString());
                    var DecisionDate = string.IsNullOrEmpty(context.Server.UrlDecode(data["txtTglSurat"])) ? (DateTime?)null : Helper.FormatDate(decodeDecisionDate, Helper.Culture.Indonesian);
                    var keputusan = context.Server.UrlDecode(data["hfRadio"]);
                    var DecisionNote = context.Server.UrlDecode(data["txtcatatan"]);
                    var DecisionValue = context.Server.UrlDecode(data["txtNilai"]);
                    var ID = context.Server.UrlDecode(data["hfID"]);
                    var objectionNo = context.Server.UrlDecode(data["hfObjectionNo"]);
                    var debtorsectorid = context.Server.UrlDecode(data["hfDebtorSectorId"]);
                    var sanctionno = context.Server.UrlDecode(data["hfSanctionNo"]);
                    var sanctionvalue = context.Server.UrlDecode(data["hfSanctionValue"]); ;
                    var SuratTanggapan = context.Server.UrlDecode(data["txtNoSuratTanggapan"]);
                    var decodeResponDate = context.Server.UrlDecode(data["txtTglTanggapan"].ToString());
                    var ResponseDate = string.IsNullOrEmpty(context.Server.UrlDecode(data["txtTglTanggapan"])) ? (DateTime?)null : Helper.FormatDate(decodeResponDate, Helper.Culture.Indonesian);
                    var transtypeid = context.Server.UrlDecode(data["hfTransTypeId"]);

                    recObjection obj = objectionDal.GetById(int.Parse(ID));
                    obj.DecisionNo = SuratKeputusan;
                    obj.DecisionDate = DecisionDate.Value;
                    obj.ResponNo = SuratTanggapan;
                    obj.ResponDate = ResponseDate;
                    obj.Decision = keputusan;
                    obj.DecisionNote = DecisionNote;
                    obj.ResponNo = SuratTanggapan;
                    obj.ResponDate = ResponseDate;
                    if (keputusan == "Diterima")
                    {
                        obj.DecisionValue = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    }
                    else if (keputusan == "Diterima Sebagian")
                    {
                        obj.DecisionValue = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    }
                    else
                        obj.DecisionValue = Helper.ToDecimal(sanctionvalue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);

                    obj.TransStatus = "Selesai";

                    if (context.Request.Files.Count > 0)
                    {
                        HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;
                        string fileName = data["name"]; // --> name taken from PLUPLOAD!

                        byte[] datas = new byte[hpf.ContentLength];
                        hpf.InputStream.Position = 0;
                        hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                        obj.DecisionFile = datas;
                        obj.FileNameDecisionFile = fileName;

                        hpf.InputStream.Close();
                        hpf.InputStream.Dispose();
                    }
                    obj.UpdatedDate = DateTime.Now;
                    obj.UpdatedBy = base.UserLoggedIn;


                    recBilling billing = new recBilling();
                    billing.ObjectionNo = objectionNo;

                    if (keputusan == "Diterima")
                    {
                        billing.Value = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        billing.Balance = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    }
                    else if (keputusan == "Diterima Sebagian")
                    {
                        billing.Value = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        billing.Balance = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    }
                    else
                    {
                        billing.Value = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        billing.Balance = Helper.ToDecimal(DecisionValue, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    }

                    if (context.Request.Files.Count > 0)
                        objectionDal.EditUpdateDecision(obj, billing);
                    else
                        objectionDal.EditUpdateDecisionWithoutFile(obj, billing);


                    helper.Message = "Data berhasil di simpan !";
                    helper.IsSuccess = true;
                }
                catch (Exception ex)
                {
                    helper.IsSuccess = false;
                    helper.Message = ex.Message;
                }
                finally
                {
                    recLog log = new recLog();
                    log.LogEvent = "Update";
                    log.LogMessage = helper.Message;
                    log.LogSource = "recObjectionHandler.ashx";
                    log.CreatedBy = base.UserLoggedIn;
                    log.CreatedDate = DateTime.Now;
                    logDal.Save(log);
                }
            }
            
            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Delete(HttpContext context, JObject jo)
        {


            JSONHelper helper = new JSONHelper();
            try
            {

                var strId = (string)jo["ObjectionID"];

                string[] ids = strId.Split(',');
                foreach (string id in ids)
                {
                    int intID = Convert.ToInt32(id);
                    objectionDal.Delete(intID);
                }

                helper.IsSuccess = true;
                helper.Message = "Data berhasil di hapus !";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Delete";
                log.LogMessage = helper.Message;
                log.LogSource = "recObjectionHandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }



    }
}
